﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WebCrawler.Crawler.Interfaces;
using WebCrawler.Crawler;
using System.Timers;
using WebCrawler.Graph;
using WebCrawler.Graph.Interfaces;
using System.Collections;

namespace WebCrawler.Gui
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ICrawler crawler;

        public MainWindow()
        {
            InitializeComponent();
            crawler = new SecondCrawler();
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            crawler.Url = txtUrl.Text;
            crawler.BuildSiteMap();

            dgVertices.ItemsSource = crawler.Graph.VerticesAsList();

            Dispatcher.Invoke(new Action(() =>
            {
                Stack<IVertex> stack = new Stack<IVertex>(crawler.Graph.VerticesAsList().Where(p => p.level == 1));

                while (stack.Any())
                {
                    IVertex vertex = stack.Pop();
                    treeView1.Items.Add(vertex);
                }
            }));
        }

        private void treeView1_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem item = (TreeViewItem)e.OriginalSource;
            Vertex vertex = (Vertex)item.DataContext;

            item.Items.Clear();

            IList adjacencies = crawler.Graph.GetAdjacencies(vertex);
            foreach (var adj in adjacencies)
            {
                item.Items.Add(adj);
            }
        }
    }
}
